<template>
  <div class="store-settled-in">
    <section class="app-main">
      <mt-field label="企业名称" placeholder="请输入企业名称" v-model="post.storeName"></mt-field>
      <mt-field label="联系人" placeholder="请输入联系人" v-model="post.linkName"></mt-field>
      <mt-field label="手机号码" placeholder="请输入手机号码" v-model="post.linkPhone"></mt-field>
      <mt-field label="验证码" placeholder="请输入验证码" v-model="post.code">
        <mt-button type="danger" class="button-send-code" :class="{disabled:validCode==false}" @click="handleGetCode">{{getCodeTitle}}</mt-button>
      </mt-field>

      <mt-field label="所在地区" placeholder="请选择所在地区" v-model="post.area" readonly="readonly" @click.native="handleSelectAddress"></mt-field>
      <mt-field label="详细地址" placeholder="请输入详细地址" v-model="post.address"></mt-field>
      <mt-cell
        title="营业执照" class="mint-field mint-field-img">
        <uploadOssImg v-bind:myFileLocate="'营业执照'" @myMediaAttr="getLicenseImg" @getAccessToken="getAccessToken"></uploadOssImg>
      </mt-cell>
      <mt-cell
        title="实体门店图" class="mint-field mint-field-img">
        <uploadOssImg v-bind:myFileLocate="'实体门店图'" @myMediaAttr="getShopImg" @getAccessToken="getAccessToken"></uploadOssImg>
      </mt-cell>

      <div class="button-content button-content-apply">
        <mt-button type="danger" @click="handleApply">申请入驻</mt-button>
      </div>
      <!--选择省市区-->

      <mt-popup
        v-model="popupAddressShow"
        position="bottom" class="popup-address">
        <selectAddress @getAddress="handleGetAddress"></selectAddress>
       </mt-popup>
      <!--选择省市区-->

      <mt-popup
        v-model="popupApplyCorrect"
        position="middle" class="popup-apply-correct">
        <span class="iconfont icon-chenggong"></span>
        <div class="correct-tips">您已提交成功，请耐心等待审核！</div>
      </mt-popup>
    </section>
  </div>
</template>

<script>
  import {Toast ,Indicator} from 'mint-ui';
  import s from '../../../static/address.json'
  import wechatAuthorize from '../../common/wechat-authorize'
  import selectAddress from '../common/select-address.vue'
  import uploadOssImg from '../common/upload-oss-img.vue'
export default {
  components:{
    selectAddress,
    uploadOssImg
  },
  data () {
    return {
      popupApplyCorrect:false,
      getCodeTitle:'获取验证码',
      validCode:true,
      popupAddressShow:false,
      licenseImgAttr:[],
      shopImgAttr:[],
      mediaAttr:[],
      myUploads:'',
      accessToken:'',
      post:{
        storeName:'',
        linkName:'',
        linkPhone:'',
        code:'',
        area:'',
        address:'',
        provinceId:'',
        cityId:'',
        districtId:'',
        storeType:3501,
        licenseImgOss:'',
        shopImgOss:'',
        openId:'',
      },
    }
  },
  beforeRouteEnter (to, from, next) {
    var u = navigator.userAgent;
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    // XXX: 修复iOS版微信HTML5 History兼容性问题
    if (isiOS && to.path !== location.pathname) {1
      // 此处不可使用location.replace
      location.assign(to.fullPath)
    } else {
      next()
    }
  },

  created(){

      /**微信授权登陆**/
//      wechatAuthorize.Authorize().then((data)=>{
//        this.post.openId=data;
//      });

//    this.accessToken='NPMZU 27__0QR0YD_BOsSHgR_MAIvYvtuKyHOuBZtWWxqQGBStajeh-Eo1GPp_uFw2PyRKSrSXlpk_xN1ROzrETLhBxUXEaxxWs0mO1pCcc69lkyYzzH9-HysV9a8pNvujBAbiZcRYM9hSMrHv7vZ0jckRTNcABAIKE'
   this.mediaAttr=[ { "serverId": "pi9McfWFjImJ7rv0l079Gpw3o_jBi0XIBLONcCR6OIQB_wtsCvMDS6k615LyXRJm", "tag": "", "fileLocate": "实体门店图" }, { "serverId": "IzXmjWpz2rFGt3o-pQbc6Kzeju03gT8HidRK4bs6Ht_Zut4HoVAj0R0V_ZbWRBgp", "tag": "", "fileLocate": "营业执照" }, { "serverId": "Lt2CP_J0x5RkZIX7lgFKDiJ9arHintg2U8NVDQKVP9w8gecD7NgnD1A660OHQ6g2", "tag": "", "fileLocate": "营业执照" } ]
  },
  methods:{

    /**获取accessToken**/
    getAccessToken(data){
      this.accessToken=data;
    },
    /**获取上传到微信的营业执照图片id**/
    getLicenseImg(data){
      this.mediaAttr=[];
      this.licenseImgAttr=data;
      this.mediaAttr=this.licenseImgAttr.concat(this.shopImgAttr)

    },
    /**获取上传到微信的门头照图片id**/
    getShopImg(data){
      this.mediaAttr=[];
      this.shopImgAttr=data;
      this.mediaAttr=this.shopImgAttr.concat(this.licenseImgAttr)

    },
    /**获取手机验证码**/
    handleGetCode(){

      var myreg=/^[1][3,4,5,7,8][0-9]{9}$/;
      if(!myreg.test(this.post.linkPhone)){
        Toast({
          message: '请输入有效的手机号码',
          position: 'middle',
          duration: 800
        });
        return false;
      }
      var time=90;
      if (this.validCode) {
        this.validCode=false;
        console.log(1111)
        var params = new URLSearchParams();
        params.append('tel',this.post.linkPhone);
        this.$axios({
          method: 'post',
          url:'gp/bu/commonUtil!sendCode.do',
          data:params
        }).then((res)=>{
          if(res.data.statusCode==200){
          Toast({
            message: '短信发送成功',
            position: 'middle',
            duration:1000
          });

        }else{
          Toast({
            message: res.data.message,
            position: 'middle',
            duration:1000
          });
        }
      })
        this.getCodeTitle=time+"秒重新获取";
        var t=setInterval(()=> {
          time--;
        this.getCodeTitle=time+"秒重新获取";
          if (time==0) {
            clearInterval(t);
            this.getCodeTitle="重新获取"
            this.validCode=true;

          }
        },1000)
      }
    },

    handleSelectAddress(){
      this.popupAddressShow=true;
    },
    /**获取选择的省市区**/
    handleGetAddress(data){
      console.log(data,111)
      this.post.area=data.title;
      this.post.provinceId=data.provinceId;
      this.post.cityId=data.cityId;
      this.post.districtId=data.districtId;
      this.popupAddressShow=false;
    },
    /**获取oss配置**/
    getOss(){
      let OSS = require('ali-oss');
      this.client = new OSS({
        region: "oss-cn-shenzhen",
        secure: true,//https
        endpoint: 'oss-cn-shenzhen.aliyuncs.com',
        accessKeyId: "LTAIPCNdQvX5yOwc",
        accessKeySecret: "7bReGAz8bc9aJdK4IAz5KW5fnNOzrQ ",
        bucket: 'rmcbapp'
      });
    },
    /**toBuffer**/
    toBuffer(ab) {
      var buf = new Buffer(ab.byteLength);
      var view = new Uint8Array(ab);
      for (var i = 0; i < buf.length; ++i) {
        buf[i] = view[i];
      }
      return buf;
    },
    /**提交申请入驻**/
    handleApply(){
      var myreg=/^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if(this.post.storeName==''){
        Toast({
          message: '请输入门店名称',
          position: 'middle',
          duration: 800
        });
        return false;
      }
      if(this.post.linkName==''){
        Toast({
          message: '请输入联系人',
          position: 'middle',
          duration: 800
        });
        return false;
      }
      if(!myreg.test(this.post.linkPhone)){
        Toast({
          message: '请输入有效的手机号码',
          position: 'middle',
          duration: 800
        });
        return false;
      }
      if(this.post.code==''){
        Toast({
          message: '请输入验证码',
          position: 'middle',
          duration: 800
        });
        return false;
      }
      if(this.post.area==''){
        Toast({
          message: '请输入所在地区',
          position: 'middle',
          duration: 800
        });
        return false;
      }
      if(this.mediaAttr.length<=0){
        Toast({
          message: '请上传营业执照',
          position: 'middle',
          duration: 800
        });
        return false;
      }


      this.getOss();
      var that=this;
      that.post.licenseImgOss='';
      that.post.shopImgOss='';
      that.myUploads=[];

      for(var i=0;i<that.mediaAttr.length;i++){

        const mediaId = that.mediaAttr[i].serverId; // 微信多媒体文件id
        const fileLocate = that.mediaAttr[i].fileLocate; // 微信多媒体文件id
        const tag = that.mediaAttr[i].tag; // 微信多媒体文件id

        if(tag==''){
          Indicator.open({
            text: '申请提交中...',
            spinnerType: 'snake'
          });
          that.$axios({
            method: 'get',
            url:'wx/cgi-bin/media/get?access_token='+that.accessToken+'&media_id='+mediaId,
            responseType:'arraybuffer',
          }).then((res)=>{
            /**arrayBuffer转Buffer**/
            var buffer = that.toBuffer(res.data);
          var destPath = 'erpStoretTest/'+fileLocate+'/'+mediaId+'.jpg'; // OSS文件路径
          that.client.put(destPath, buffer).then((result) => {
            console.log('图片上传阿里云结果', result);
          var item='https://rmcbapp.oss-cn-shenzhen.aliyuncs.com/'+result.name;
          if(fileLocate=='营业执照'){
            if(that.post.licenseImgOss==''){
              that.post.licenseImgOss+=item;
            }else{
              that.post.licenseImgOss+=','+item;
            }
          }else if(fileLocate=='实体门店图'){
            if(that.post.shopImgOss==''){
              that.post.shopImgOss+=item;
            }else{
              that.post.shopImgOss+=','+item;
            }
          }
          that.myUploads.push(item);
          if(that.myUploads.length==i){
            /**图片全部上传到阿里云**/
            that.handlePostApi();
          }

        }).catch((err) => {
            Indicator.close();
            console.log(err)
            Toast({
              message: '图片上传失败',
              position: 'middle',
              duration:1000
            });
         });
        })
        }else{
          Indicator.close();
          console.log('该图片已上传')
        }
      };
    },

    handlePostApi(){

        if(this.post.licenseImgOss==''){
          Indicator.close();
          Toast({
            message: '请上传营业执照',
            position: 'middle',
            duration: 800
          });
          return false;
        }
        if(this.post.shopImgOss==''){
          Indicator.close();
          Toast({
            message: '请上传实体门店图',
            position: 'middle',
            duration: 800
          });
          return false;
        }
        var params = new URLSearchParams();
        params.append('form.storeName',this.post.storeName);
        params.append('form.name',this.post.linkName);
        params.append('form.mobile',this.post.linkPhone);
        params.append('form.province',this.post.provinceId);
        params.append('form.city',this.post.cityId);
        params.append('form.districtId',this.post.districtId);
        params.append('form.storeAddress',this.post.address);
        params.append('form.code',this.post.code);
        params.append('form.openId',this.post.openId);
        params.append('form.licenseImgOss',this.post.licenseImgOss);
        params.append('form.shopImgOss',this.post.shopImgOss);
        this.$axios({
          method: 'post',
          url:'gp/bu/storeApply!saveApply.do',
          data:params
        }).then((res)=>{
          if(res.data.statusCode==200){
          Indicator.close();
          this.popupApplyCorrect=true;
        }else{
          Indicator.close();
          Toast({
            message: res.data.message,
            position: 'middle',
            duration:1000
          });
        }
      }).catch((error)=> {
          Indicator.close();
        Toast({
          message: error,
          position: 'middle',
          duration:2000
        });
      });
    },
  }
}
</script>
<style>

  .store-settled-in .button-content-apply{
    padding:24px 32px;
  }
  .store-settled-in .button-content-apply .mint-button--normal{
    background: -webkit-linear-gradient(left, #03adf3 , #0080e5); /* Safari 5.1 - 6.0 */
    background: -o-linear-gradient(right, #03adf3 , #0080e5); /* Opera 11.1 - 12.0 */
    background: -moz-linear-gradient(right, #03adf3 , #0080e5); /* Firefox 3.6 - 15 */
    background: linear-gradient(to right, #03adf3 , #0080e5); /* 标准的语法 */
    width: 100%;
  }
  .store-settled-in .button-send-code{
    background: #007EE5;
    font-size: 15px;
    height:34px;
  }
  .store-settled-in .button-send-code.disabled{
    background: #999;
  }
  .store-settled-in .popup-apply-correct{
    width: 100%;
    height: 100%;
    padding:120px 0 0;
    text-align: center;
  }
  .store-settled-in .popup-apply-correct .icon-chenggong{
    color: #007EE5;
    font-size: 60px;
  }
  .store-settled-in .popup-apply-correct .correct-tips{
    padding:12px 0 0;
    font-size: 16px;
    color: #555;
  }
</style>
<!-- Add "scoped" attribute to limit CSS to this component only -->

